import React, { useContext, useState } from 'react';
import { Modal, Button, Space, Form, Typography, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { RcFile } from 'antd/es/upload';
import { useParams } from 'react-router-dom';

import ServoLimitationComponent from '../components/ServoLimitationComponent';
import PageHeader from './layouts/PageHeader';
import SerialDeviceSelectView from '../views/SerialDeviceSelectView';
import SerialBaudRateSelectView from '../views/SerialBaudRateSelectView';
import Operation from './layouts/Operation';
import { convertFileToBase64 } from '../utils/base64';
import { SerialContext } from '../context/SerialContext';
import './ServoDetail.css';

const DEFAULT_BAUDRATE = 115200;

export default function Settings() {
  const { id } = useParams();
  const ctx = useContext(SerialContext);

  if (!ctx) return null;

  const { serialState, setSerialState, globalModel, servoModel } = ctx;

  const [settingOpen, setSettingOpen] = useState(false);
  const [upgradeOpen, setUpgradeOpen] = useState(false);
  const [firmwareFile, setFirmwareFile] = useState<File | null>(null);
  const [fileList, setFileList] = useState<any[]>([]);
  const [form] = Form.useForm();

  const onUpgrade = () => setUpgradeOpen(true);
  const onSettings = () => setSettingOpen(true);

  const doUpgrade = async () => {
    if (!firmwareFile) return message.error('请选择固件文件');

    try {
      const base64 = await convertFileToBase64(firmwareFile);
      setSerialState({ ...serialState, isSerialUpgrade: true });

      await window.electron.ipcRenderer.invoke(
        'firmware-upgrade-stream',
        form.getFieldValue('device'),
        form.getFieldValue('baudrate'),
        base64,
        id
      );

      message.success('升级成功');
    } catch (err) {
      console.error(err);
      message.error('升级失败');
    } finally {
      setSerialState({ ...serialState, isSerialUpgrade: false });
      handleModalClose();
    }
  };

  const handleUpload = (file: RcFile) => {
    const isValid = file.name.endsWith('.bin') || file.name.endsWith('.hex');
    if (!isValid) {
      message.error('仅支持 .bin 或 .hex 格式的固件文件');
      return Upload.LIST_IGNORE;
    }

    setFirmwareFile(file);
    setFileList([file]);
    message.success('文件上传成功');
    return false;
  };

  const handleModalClose = () => {
    setUpgradeOpen(false);
    setFirmwareFile(null);
    setFileList([]);
    form.resetFields();
  };

  return (
    <div>
      <PageHeader
        title={`舵机 ID: ${id}`}
        extra={
          <Space align="center">
            <Typography.Text className="mode-display">
              当前模式：
              <span
                className={servoModel.servoMode ? 'mode-servo' : 'mode-motor'}
              >
                {servoModel.servoMode ? '舵机模式' : '电机模式'}
              </span>
            </Typography.Text>
            <Button onClick={onUpgrade}>升级</Button>
            <Button type="primary" onClick={onSettings}>
              设置
            </Button>
          </Space>
        }
      />

      <Operation />

      {/* 设置弹窗 */}
      <Modal
        open={settingOpen}
        title="舵机限制设置"
        onCancel={() => setSettingOpen(false)}
        footer={null}
        width={850}
        destroyOnClose
      >
        <ServoLimitationComponent />
      </Modal>

      {/* 升级弹窗 */}
      <Modal
        open={upgradeOpen}
        title="固件升级"
        onCancel={handleModalClose}
        onOk={doUpgrade}
        okText="更新"
        cancelText="取消"
        destroyOnHidden
        confirmLoading={serialState.isSerialUpgrade}
        okButtonProps={{
          disabled: !firmwareFile || serialState.isSerialUpgrade,
        }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            device: globalModel.global_serial_id || '',
            baudrate: DEFAULT_BAUDRATE,
          }}
        >
          <Form.Item>
            <Typography.Paragraph type="secondary">
              请确保选择正确的串口设备和波特率，并上传匹配的固件文件。升级过程中请勿断开连接。
            </Typography.Paragraph>
          </Form.Item>

          <Form.Item label="舵机 ID">
            <Typography.Text>{id}</Typography.Text>
          </Form.Item>

          <Form.Item
            name="device"
            label="设备"
            rules={[{ required: true, message: '请选择串口设备' }]}
          >
            <SerialDeviceSelectView />
          </Form.Item>

          <Form.Item
            name="baudrate"
            label="波特率"
            rules={[{ required: true, message: '请选择波特率' }]}
          >
            <SerialBaudRateSelectView />
          </Form.Item>

          <Form.Item label="固件文件" required>
            <Upload
              beforeUpload={handleUpload}
              fileList={fileList}
              onRemove={() => {
                setFirmwareFile(null);
                setFileList([]);
              }}
              showUploadList
            >
              <Button icon={<UploadOutlined />}>
                选择固件文件（.bin/.hex）
              </Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
